package name.williamwall.buxoid;
/**
 * This software is made available under the Gnu General Public License v3
 * and has absolutely no waranty. You may change the software to suit your needs.
 * 
 * Author: William Wall, IV
 */
import java.text.NumberFormat;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class BudgetAdapter extends SimpleCursorAdapter {
	private static NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
	private int mWidth;
	private double mSpent;
	private Context mContext;
	
	public BudgetAdapter(Context context, int layout, Cursor c, String[] from, int [] to, int month, int year, BuxoidDb db) {
		super(context, layout, c, from, to);
		mContext = context;
		DisplayMetrics dm = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
		mWidth = dm.widthPixels;
		moneyFormat.setCurrency(Buxoid.mDb.getCurrency());
	}

	@Override
	public void setViewImage(ImageView v, String value) {
		int id = v.getId();
		if (id == R.id.row_budget_bar) {
			Cursor c = super.getCursor();
			// get the tag limit
			double limit = c.getDouble(c.getColumnIndexOrThrow(BuxoidDb.TAG_LIMIT));
			
			// compute the percent spent 
			double percent = mSpent / limit;
			
			// compute the width of the bar in screen pixels
			int width = (int) Math.floor(Math.min(percent, 1) * mWidth);
			
			// can't have zero width, so give it 1px for 0
			width = Math.max(width, 1);
			
			// load the image
			BitmapDrawable d = (BitmapDrawable) mContext.getResources().getDrawable(percent > 1 ? R.drawable.overbudget: R.drawable.underbudget);
			
			// resize it to width
			Bitmap b = Bitmap.createScaledBitmap(d.getBitmap(), width, 11, false);
			
			// set the image view to contain the new image
			v.setImageBitmap(b);
		} else {
			super.setViewImage(v, value);
		}
	}

	@Override
	public void setViewText(TextView v, String text) {
		int id = v.getId();
		if (id == R.id.row_budget_amount) {
			Cursor c = super.getCursor();
			mSpent = c.getDouble(c.getColumnIndex(BuxoidDb.ANALYSIS_AMOUNT));
			v.setText(moneyFormat.format(mSpent) + " / " + moneyFormat.format(Double.parseDouble(text)));
		} else {
			super.setViewText(v, text);
		}
	}
}
